<template>
  <div class="singer">
  	<list-view @select="selectSinger" :data="singers"></list-view> 
    <router-view></router-view>
  </div>
</template>

<script type="text/ecmascript-6">
  import {getSignerList} from 'api/singer'
  import {ERR_OK} from 'api/config'
  import Singer from 'common/js/singer'
  import ListView from 'base/listview/listview'
  import {mapMutations} from 'vuex'

  const HOT_NAME = "热门"
  const HOT_SINGER_LEN = 10
  export default {
  	data() {
  		return {
  			singers: []
  		}
  	},
  	created() {
  		this._getSignerList()
  	},
    components: {
      ListView
    },
  	methods: {
      selectSinger(singer) {
         this.$router.push({
          path: `/singer/${singer.id}`
        })
         this.setSinger(singer);
      },
  		_getSignerList() {
		  getSignerList().then((res) => {
		  	if (res.code == ERR_OK) {
		  		this.singers = res.data.list
		  		this.singers = this._normallizeSinger(this.singers)
		  	}
		  })
  		},
  		_normallizeSinger(list) {
  			let map = {
  				hot: {
  					title: HOT_NAME,
  					item: []
  				}

  			}
  			list.forEach((item,index) => {
  			  if (index < HOT_SINGER_LEN) {
  			  	map.hot.item.push(new Singer({
			  		id: item.Fsinger_mid,
  			  		name: item.Fsinger_name,
  			  	}))
  			  }
  			  const key = item.Findex
	  			if (!map[key]) {
	  				map[key] = {
	  					title: key,
	  					item: []
	  				}
	  			}
	  			map[key].item.push(
	  				new Singer({
				  		id: item.Fsinger_mid,
	  			  		name: item.Fsinger_name,
	  			  	})
	  			  	)
	  		})
	  		// 为了得到有序列表，我们需要处理 map
	        let ret = []
	        let hot = []
	        for (let key in map) {
	          let val = map[key]
	          if (val.title.match(/[a-zA-Z]/)) {
	            ret.push(val)
	          } else if (val.title === HOT_NAME) {
	            hot.push(val)
	          }
	        }
	        ret.sort((a, b) => {
	          return a.title.charCodeAt(0) - b.title.charCodeAt(0)
	        })
	        return hot.concat(ret)	

  		},
      ...mapMutations({
        setSinger: 'SET_SINGER'
      })
  	}
  }
</script>

<style scoped lang="stylus" res="stylesheet/stylus">
  @import "~common/stylus/variable"
  .singer
  	position:fixed
  	top:88px
  	width:100%
  	bottom:0
</style>
